package twitter.client.task;

import java.util.List;

import twitter.client.adapter.TimelineListAdapter;
import twitter.client.util.Global;
import twitter.client.util.Utils;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.AbsListView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.WrapperListAdapter;

public class GetTimelineTask extends AsyncTask<Twitter, Void, Void> {

	private AbsListView view;
	private TimelineListAdapter adapter;

	public GetTimelineTask(AbsListView view) {
		this.view = view;
	}

	@Override
	protected Void doInBackground(Twitter... params) {
		Twitter twitter = params[0];

		ResponseList<twitter4j.Status> timelineData = null;
		try {
			if (Global.timelineStatus.getMaxId() > 0) {
				Paging paging = new Paging();
				paging.setMaxId(Global.timelineStatus.getMaxId());
				timelineData = twitter.getHomeTimeline(paging);
			} else {
				timelineData = twitter.getHomeTimeline();
			}

			if (timelineData == null || timelineData.isEmpty()) {
				Global.timelineStatus.setLast(true);
			} else {
				Global.timelineStatus.setSinceId(timelineData.get(0).getId());
				Global.timelineStatus.setMaxId(timelineData.get(
						timelineData.size() - 1).getId() - 1);
			}

			ListAdapter listAdapter = view.getAdapter();
			if (listAdapter instanceof WrapperListAdapter) {
				WrapperListAdapter tmp = (WrapperListAdapter) listAdapter;
				this.adapter = (TimelineListAdapter) tmp.getWrappedAdapter();
			} else {
				this.adapter = (TimelineListAdapter) listAdapter;
			}

			List<twitter4j.Status> currentList = this.adapter.getData();
			
			a
			
			currentList.addAll(timelineData);

			// timeline.setAdapter(new TimelineListAdapter(this,
			// R.layout.timeline, new ArrayList<twitter4j.Status>()));
		} catch (TwitterException e) {
			Log.e("TwitterException", "", e);
			Utils.showToast(this.view.getContext().getApplicationContext(),
					e.getMessage());
		}

		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		adapter.notifyDataSetChanged();
		// LayoutInflater inflater = (LayoutInflater) this.view
		// .getContext().getApplicationContext().getSystemService(
		// Context.LAYOUT_INFLATER_SERVICE);
		// View footer = inflater.inflate(R.layout.footer_loading, null);
		boolean b = ((ListView) view)
				.removeFooterView(Global.loadingFooterView);
		Log.d("onPostExecute", "b : " + b);
	}
}
